package adapter.company;

import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.trek2000.android.enterprise.Enterprise;
import com.trek2000.android.enterprise.R;
import java.util.ArrayList;

import de.hdodenhof.circleimageview.CircleImageView;
import define.API;
import model.company.SelectCompanyItem;
import ui.activity.login.Login;
import ui.fragment.company.AllCompanyFeedFragment;
import ui.fragment.company.CompanyFeedFragment;
import ui.fragment.drawer.NavigationDrawerFragment;


/**
 * Created by trek2000 on 21/8/2014.
 */
public class SelectCompanyAdapter extends BaseAdapter {

    /**
     * Data section
     */
    public static ArrayList <SelectCompanyItem> mAlSelectCompany = new ArrayList<>();

    /**
     * Interface section
     */

    /**
     * String section
     */
    private int textViewResourceId;
    /**
     * The other section
     */
    private Context mContext;
    private DisplayImageOptions mDio;
    private ViewHolder viewHolder;

    private class ViewHolder {
        private CircleImageView circleIvItem;
        private ImageView mIvBadge;
        private TextView mTvBadgeNumber;
        private TextView mTvCompanyName;
        private TextView mTvCompanyNumber;
    }

    /**
     * @param context
     */
    public SelectCompanyAdapter(Context context, int textViewResourceId, ArrayList <SelectCompanyItem> mAlselectCompany) {
        this.mContext = context;
        this.textViewResourceId = textViewResourceId;
        this.mAlSelectCompany = mAlselectCompany;

        mDio = new DisplayImageOptions.Builder()
                .delayBeforeLoading(1000)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
    }

    /**
     * @return
     */
    public int getCount() {
        return mAlSelectCompany.size();
    }

    /**
     * @param position
     * @return
     */
    public SelectCompanyItem getItem(int position) {
        return mAlSelectCompany.get(position);
    }

    /**
     * @param position
     * @return
     */
    public long getItemId(int position) {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(final int pos, View convertView, ViewGroup parent) {

        if (convertView == null) {
            viewHolder = new ViewHolder();
            LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(textViewResourceId, null);
            viewHolder.mIvBadge = (ImageView) convertView.findViewById(R.id.iv_badge_in_simple_list_item_select_company);
            viewHolder.circleIvItem = (CircleImageView) convertView.findViewById(R.id.circleiv_item_in_simple_list_item_select_company);
            viewHolder.mTvBadgeNumber = (TextView) convertView.findViewById(R.id.tv_badge_number_in_simple_list_item_select_company);
            viewHolder.mTvCompanyName = (TextView) convertView.findViewById(R.id.tv_company_name_in_simple_list_item_select_company);
            viewHolder.mTvCompanyNumber = (TextView) convertView.findViewById(R.id.tv_company_number_in_simple_list_item_select_company);

            viewHolder.mIvBadge.setTag(pos);
            viewHolder.circleIvItem.setTag(pos);
            viewHolder.mTvBadgeNumber.setTag(pos);
            viewHolder.mTvCompanyName.setTag(pos);
            viewHolder.mTvCompanyNumber.setTag(pos);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder)convertView.getTag();

            viewHolder.mIvBadge.setTag(pos);
            viewHolder.circleIvItem.setTag(pos);
            viewHolder.mTvBadgeNumber.setTag(pos);
            viewHolder.mTvCompanyName.setTag(pos);
            viewHolder.mTvCompanyNumber.setTag(pos);
        }

        //set data
        switch (pos) {
            case 0:
                viewHolder.circleIvItem.setImageResource(R.drawable.ibtn_all);
                viewHolder.mTvCompanyName.setText(mContext.getString(R.string.all_company));
                break;
            default:
                viewHolder.mTvCompanyName.setText(mAlSelectCompany.get(pos).getName());

                try {
                    String URL = "";
                    if (API.IS_DEV_SITE)
                        URL = mAlSelectCompany.get(pos).getLogoUrl().replace("https", "http");
                    else
                        URL = mAlSelectCompany.get(pos).getLogoUrl();

                    Enterprise.imageLoader.displayImage(
                            URL,
                            viewHolder.circleIvItem, mDio,
                            new SimpleImageLoadingListener() {
                                @Override
                                public void onLoadingStarted(String imageUri, View view) {
                                }

                                @Override
                                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                                }

                                @Override
                                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                                    if (loadedImage != null & view.findViewWithTag(pos) != null) {
                                        ((ImageView) view.findViewWithTag(pos)).setImageBitmap(loadedImage);
                                    }
                                }
                            }, new ImageLoadingProgressListener() {
                                @Override
                                public void onProgressUpdate(
                                        String imageUri, View view, int current, int total) {
                                }
                            });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            break;
        }

        //on click listener
        viewHolder.circleIvItem.findViewWithTag(pos).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (pos) {
                    case 0:
                        // go to All company feed
                        ((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(
                                R.id.fl_in_activity_enterprise, AllCompanyFeedFragment.newInstance()
                        ).commitAllowingStateLoss();
                        Enterprise.mTvTitle.setText(mContext.getString(R.string.all_company));
                        Enterprise.mIvArrowInActionBar.setImageResource(R.drawable.iv_arrow_down);
                        Enterprise.mIvArrowInActionBar.setVisibility(View.VISIBLE);
                        break;
                    default:
                        // go to company feed
                        ((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(
                                R.id.fl_in_activity_enterprise, CompanyFeedFragment.newInstance()
                        ).commitAllowingStateLoss();
                        Enterprise.company.setPositionOfSelectCompanyItem(pos);
                        Enterprise.mTvTitle.setText(mAlSelectCompany.get(pos).getName());
                        Enterprise.mIvArrowInActionBar.setImageResource(R.drawable.iv_arrow_down);
                        Enterprise.mIvArrowInActionBar.setVisibility(View.VISIBLE);
                        /**
                         * compare company id of company selected and company id of login user info
                         * to get company id, company id group, user company id
                         * because one user join manny company with many user company id others
                         */
                        for (int i = 0 ; i < Login.user.getUserInfo().getmAlCompaniesOfUserInfo().size(); i++) {
                            if (Login.user.getUserInfo().getmAlCompaniesOfUserInfo().get(i).getCompanyId() ==
                                    mAlSelectCompany.get(pos).getCompanyId()) {
                                Enterprise.company.setCompaniesOfUserInfoSelected(Login.user.getUserInfo().getmAlCompaniesOfUserInfo().get(i));
                            }
                        }
                        //save company name to single ton to use for api invite user to company
                        Enterprise.company.setCompanyNameSelected(
                                mAlSelectCompany.get(pos).getName()
                        );
                        //reset login and company name
                        NavigationDrawerFragment.resetCompanyLogoAndNameInNavigationDrawerFragment();
                        break;
                }
            }
        });

        viewHolder.mTvCompanyName.findViewWithTag(pos).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (pos) {
                    case 0:
                        // go to All company feed
                        ((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(
                                R.id.fl_in_activity_enterprise, AllCompanyFeedFragment.newInstance()
                        ).commitAllowingStateLoss();
                        Enterprise.mTvTitle.setText(mContext.getString(R.string.all_company));
                        Enterprise.mIvArrowInActionBar.setImageResource(R.drawable.iv_arrow_down);
                        Enterprise.mIvArrowInActionBar.setVisibility(View.VISIBLE);
                        break;
                    default:
                        // go to company feed
                        ((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(
                                R.id.fl_in_activity_enterprise, CompanyFeedFragment.newInstance()
                        ).commitAllowingStateLoss();
                        Enterprise.company.setPositionOfSelectCompanyItem(pos);
                        Enterprise.mTvTitle.setText(mAlSelectCompany.get(pos).getName());
                        Enterprise.mIvArrowInActionBar.setImageResource(R.drawable.iv_arrow_down);
                        Enterprise.mIvArrowInActionBar.setVisibility(View.VISIBLE);
                        /**
                         * compare company id of company selected and company id of login user info
                         * to get company id, company id group, user company id
                         * because one user join manny company with many user company id others
                         */
                        for (int i = 0 ; i < Login.user.getUserInfo().getmAlCompaniesOfUserInfo().size(); i++) {
                            if (Login.user.getUserInfo().getmAlCompaniesOfUserInfo().get(i).getCompanyId() ==
                                    mAlSelectCompany.get(pos).getCompanyId()) {
                                Enterprise.company.setCompaniesOfUserInfoSelected(Login.user.getUserInfo().getmAlCompaniesOfUserInfo().get(i));
                            }
                        }
                        //save company name to single ton to use for api invite user to company
                        Enterprise.company.setCompanyNameSelected(
                                mAlSelectCompany.get(pos).getName()
                        );
                        //reset login and company name
                        NavigationDrawerFragment.resetCompanyLogoAndNameInNavigationDrawerFragment();
                }
            }
        });
        return convertView;
    }

}